package io.renren.modules.service.impl;

import feign.Client;
import feign.Contract;
import feign.Feign;
import feign.codec.Decoder;
import feign.codec.Encoder;
import io.renren.modules.service.IFeignClientCreateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClientsConfiguration;
import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient;
import org.springframework.context.annotation.Import;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Import(FeignClientsConfiguration.class)
public class FeignClientCreateServiceImpl implements IFeignClientCreateService {

  private final Feign.Builder urlBuilder;

  private Map<String, Object> clientCached = new ConcurrentHashMap<>();

  @Autowired
  public FeignClientCreateServiceImpl(Decoder decoder, Encoder encoder, Client client, Contract contract) {
    if (client instanceof LoadBalancerFeignClient) {
      client = ((LoadBalancerFeignClient) client).getDelegate();
    }
    urlBuilder = Feign.builder().client(client)
        .encoder(encoder)
        .decoder(decoder)
        .contract(contract);
  }

  @Override
  @SuppressWarnings("unchecked")
  public <T> T newClientByUrl(Class<T> clientType, String url) {
    Object obj = clientCached.get(url);
    if (obj != null) {
      return (T) obj;
    }

    T client = urlBuilder.target(clientType, url);
    clientCached.put(url, client);
    return client;
  }
}
